package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.mobileim.YWIMKit;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMManager;
import com.tencent.qcloud.timchat.utils.LoginBusiness;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.listener.ILoginSMSCodeListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.manager.LoginSMSCodeManager;
import com.wbao.dianniu.utils.KeyboardHeightHandler;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

/**
 * 短信验证码登录
 * <p>
 * Created by yejianjun on 2017/11/7.
 */

public class MsgLoginActivity extends BaseActivity implements ILoginSMSCodeListener, ILoginListener,TIMCallBack {

    private static final String TAG = MsgLoginActivity.class.getSimpleName();
    private Button loginBtn;
    private TextView authCodeTV;
    private EditText mobileEditText;
    private EditText authCdoeEditText;
    private int count = 0;
    private LoginManager manager;
    private LoginSMSCodeManager smsCodeManager;
    private YWIMKit mIMKit;
    private Dialog pDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Utils.setTranslucentStatus(this, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
        }*/
        setContentLayout(R.layout.activity_message_login, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        setTitleName(R.string.message_login);
        initView();
        initData();
        if (0 == SharedPreferencesUtils.getKeyboardHeight(this)) {
            KeyboardHeightHandler handler = new KeyboardHeightHandler();
            handler.getKeyboardHeight(this);
        }
    }

    private void initView() {
        loginBtn = (Button) findViewById(R.id.msg_login_btn);
        authCodeTV = (TextView) findViewById(R.id.msg_login_authCode);
        mobileEditText = (EditText) findViewById(R.id.msg_login_mobile);
        authCdoeEditText = (EditText) findViewById(R.id.msg_login_code);
        authCodeTV.setOnClickListener(noDoubleClickListener);
        loginBtn.setOnClickListener(noDoubleClickListener);
        authCdoeEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }

    private void initData() {
        manager = new LoginManager(this);
        manager.addLoginListener(this);
        smsCodeManager = new LoginSMSCodeManager(this);
        smsCodeManager.addLoginSmsCodeListener(this);
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            authCodeTV.setText(millisUntilFinished / 1000 + getResources().getString(R.string.auth_code_get_desc));
        }

        @Override
        public void onFinish() {
            authCodeTV.setEnabled(true);
            authCodeTV.setText(getResources().getString(R.string.register_get_auth_password));
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        if (null != timer) {
            timer.cancel();
        }
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != manager) {
            manager.removeLoginListener(this);
        }
        if (null != smsCodeManager) {
            smsCodeManager.removeLoginSmsCodeListener(this);
        }
    }

    NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            String mobile = mobileEditText.getText().toString().trim();
            String authCode = authCdoeEditText.getText().toString().trim();
            switch (v.getId()) {
                case R.id.msg_login_btn:
                    if (authMobile(mobile)) {
                        if (count > 5) {
                            Notification.toast(MsgLoginActivity.this, getResources().getString(R.string.register_error_5_toast));
                            return;
                        }
                        showWaittingDialog();
                        String pushClientId = SharedPreferencesUtils.getClientId(MsgLoginActivity.this);
                        manager.Login(MsgLoginActivity.this, mobile, null, Utils.getDeviceId(MsgLoginActivity.this), null, null, Utils.getVersionName(MsgLoginActivity.this), authCode, pushClientId);
                    }
                    break;
                case R.id.msg_login_authCode:
                    //获取验证码
                    if (authMobile(mobile)) {
                        /** 每次获取验证码，清除错误累计 */
                        count = 0;
                        v.setEnabled(false);
                        authCodeTV.setBackgroundResource(R.drawable.get_code_unpress);
                        timer.start();
                        smsCodeManager.getLoginSmsCode(mobile);
                    }
                    break;
                default:
                    break;
            }

        }
    };


    private boolean authMobile(String mobile) {
        boolean ret = false;
        if (null == mobile) {
            toastString(getResources().getString(R.string.register_error_1));
            return ret;
        } else {
            boolean ismobile = mobile.matches("^(13|15|18|14|17)\\d{9}$");
            if (ismobile) {
                ret = true;
            } else {
                toastString(getResources().getString(R.string.login_error_1));
            }
            return ret;
        }
    }

    private void toastString(String message) {
        Notification.toast(MsgLoginActivity.this, message);
    }

    @Override
    public void onLoginSmsFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onLoginSmsSuccess() {

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        toastString(errorMsg == null ? "" : errorMsg);
        count++;
    }

    @Override
    public void onLoginSuccess(LoginResponse objdata) {
        /** 清除登录错误次数累加	*/
        SharedPreferencesUtils.setLoginErrorCount(this, 0);
        Utils.saveLoginData(this, objdata);
//        loginTencentIM(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getTencentImUserSig(), objdata.getAccountInfo().getPwd());

//        init(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), getResources().getString(R.string.app_key));
        //登录成功时，登录IM
//        loginIM(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getAccountInfo().getPwd());

        saveConfigInfo(objdata.getAccountInfo().getPwd());
        LoginBusiness.loginIm(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getTencentImUserSig(),this);

    }


    private void saveConfigInfo(String pwd) {
        SharedPreferencesUtils.init(MsgLoginActivity.this);
        SharedPreferencesUtils.setUserName(this, mobileEditText.getText().toString());
        SharedPreferencesUtils.setPassword(this, pwd);
        SharedPreferencesUtils.setAutoLoginStatus(this, true);
    }

    private void showWaittingDialog() {
        pDialog = LoadingDialog.createLoadingDialog(this, "正在登录...");
        pDialog.show();
    }

    @Override
    public void onError(int i, String s) {
        switch (i) {
            case 6208:
                Log.e(TAG,"离线状态下被其他终端踢下线... 再次登录");
                //离线状态下被其他终端踢下线
                // 再次掉登录接口
                GlobalUserData userData = new GlobalUserData();
                LoginBusiness.loginIm(userData.getEnvironemt() + GlobalContext.getAccountId(), userData.getUserSig(), MsgLoginActivity.this);
                break;
            case 6200:
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Notification.toast(MsgLoginActivity.this, getString(R.string.login_error_timeout));
                break;
            default:
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Notification.toast(MsgLoginActivity.this, "【登录失败，错误码】：" + i);
                break;
        }
    }

    @Override
    public void onSuccess() {


        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        // 成功 界面跳转
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setClass(MsgLoginActivity.this, MainActivity.class);
        startActivity(intent);
        MsgLoginActivity.this.finish();

    }
}
